const fs = require('fs');
const { fileUtils } = require('./FileUtils.js');
const { JackTokenizer } = require('./JackTokenizer.js');
const { CompilationEngine } = require('./CompilationEngine.js');

class JackAnalyzer {
  constructor(tokenizer, compilationEngine, filePaths) {
    this.tokenizer = tokenizer;
    this.compilationEngine = compilationEngine;
    this.filePaths = filePaths;
  }

  run() {
    this.filePaths.forEach((fileConfig) => {
      this.processOneFile(fileConfig);
    });
  }

  processOneFile({ input, output }) {
    this.tokenizer.reset(fs.readFileSync(input).toString());
    const tokens = [];

    while (this.tokenizer.hasMoreTokens()) {
      this.tokenizer.advance();
      tokens.push(this.tokenizer.getClonedCurrentToken());
    }

    this.compilationEngine.generateParseTree(tokens);
    const xml = this.compilationEngine.convertParseTreeToXml();
    fs.writeFileSync(output, xml);
  }
}

const filePaths = fileUtils.getFilePaths();
const tokenizer = new JackTokenizer();
const engine = new CompilationEngine();
const analyzer = new JackAnalyzer(tokenizer, engine, filePaths);
analyzer.run();
